package framework.dao.mybatis.util;

import framework.dao.exception.DataAccessException;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {


    private static SqlSessionFactory sessionFactory;
    private static ThreadLocal<SqlSession> threadLocal;

    static {
        try {
            threadLocal=new ThreadLocal<SqlSession>();

            sessionFactory=new SqlSessionFactoryBuilder()
                    .build(MyBatisUtil.class
                            .getClassLoader()
                            .getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("MyBatisUtil初始化失败");
        }
    }

    public static SqlSession getSession(){
        SqlSession session=threadLocal.get();
        if(session==null){
            try {

                session=sessionFactory.openSession();

                threadLocal.set(session);

            } catch (Exception e) {
                e.printStackTrace();
                throw new DataAccessException("数据访问失败", e);
            }
        }
        return session;
    }

    public static void close(){
        SqlSession session=threadLocal.get();
        if(session!=null){
            session.close();
        }
        threadLocal.remove();
    }
}
